import cn.hutool.core.util.StrUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author huangy
 * @since 2022/8/27 2:41 下午
 */
public class RandomWords implements Supplier<String> {

    List<String> words = new ArrayList<>();
    Random rand = new Random();

    RandomWords(String fName) {
        try (BufferedReader reader = IOUtil.getBufferedReaderFromFileName(fName)) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (StrUtil.isNotBlank(line)) {
                    System.out.println(line);
                    words.add(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void collectsToTreeMap(String fName) throws IOException {
        Set<String> words = Files.lines(Paths.get("RandomWords.java"))
                .flatMap(s -> Arrays.stream(s.split("\\w+")))
                .filter(s -> !s.matches("\\d+"))
                .map(String::trim)
                .filter(s -> s.length() > 2)
                .limit(100)
                .collect(Collectors.toCollection(TreeSet::new));
        System.out.println(words);
    }

    @Override
    public String get() {
        return words.get(rand.nextInt(words.size()));
    }

    @Override
    public String toString() {
        return String.join(" ", words);
    }

    public static void main(String[] args) throws IOException {
        collectsToTreeMap("春江花月夜.txt");
    }

}
